package com.kaili.basic.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kaili.basic.mapper.BaseEmployeeMapper;
import com.kaili.basic.pojo.dto.MdmUserUpdateBaseRolesDto;
import com.kaili.basic.pojo.entity.MdmCompany;
import com.kaili.basic.service.IBaseEmployeeService;
import com.kaili.basic.service.BaseUserService;
import com.kaili.common.pojo.entity.BaseEmployee;
import com.kaili.common.pojo.entity.BaseUser;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.tenant.DbContextHolder;
import com.kaili.common.util.CommonConstant;
import com.kaili.common.util.HexStringUtils;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.common.util.SHA256Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * Created by rzh on 18-5-8.
 */
@Service
public class BaseEmployeeServiceImpl extends ServiceImpl<BaseEmployeeMapper, BaseEmployee> implements IBaseEmployeeService {

    @Autowired
    BaseUserService baseUserService;
    @Override
    public boolean updateById(BaseEmployee entity) {
        return super.updateById(entity);
    }

    @Override
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }

    @Override
    @Transactional
    public boolean insertOrUpdate(BaseEmployee entity) {
        Boolean add = true;
        if(entity.getId() != null){
            add = false;
        }
        boolean flag = super.insertOrUpdate(entity);
        if(add){
            Map<String, Object> map=new HashMap<>();
            map.put("accountTypeId",3);
            map.put("dataId",entity.getId());
            return true;
        }
        return false;
    }

    @Override
    public Page<BaseEmployee> selectByMap(Page<BaseEmployee> page, BaseEmployee baseEmployee) {
        return page.setRecords(baseMapper.selectByMap(page, baseEmployee));
    }

    public List<BaseEmployee> exportByMap(BaseEmployee baseEmployee){
        return baseMapper.exportByMap(baseEmployee);
    }

    @Override
    public Page<BaseEmployee> selectByPar(Page<BaseEmployee> page, String par, Integer par1) {
        return page.setRecords(baseMapper.selectByPar(page, par, par1));
    }

    @Override
    public BaseEmployee selectById(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public String getCode() {
        return baseMapper.getCode();
    }

    @Override
    public List<BaseEmployee> exportBaseEmployeeQueryList(Map map) {
        return baseMapper.exportBaseEmployeeQueryList(map);
    }

    @Override
    public BaseEmployee getEmpByName(String empName) {
        return baseMapper.getEmpByName(empName);
    }


    public int updatePasswordById(Map<String,Object> params){
        return baseMapper.updatePasswordById(params);
    }


    private int createAccount(BaseEmployee baseEmployee){
        BaseUser user = new BaseUser();
        user.setPassword(baseEmployee.getPassword());
        user.setUsername(baseEmployee.getEmployeeName());
        user.setEmployeeId(baseEmployee.getId());
        user.setCompanyId(baseEmployee.getCompanyId());
        Long[] rids = {baseEmployee.getRid().longValue()};
        user.setRids(rids);
        //判断用户是否超过系统设置用户
        Integer count=baseUserService.selectCountAccount();//已创建用户
        //查询公司能用多少用户
        MdmCompany mdmCompany=userCount();
        if(count<=mdmCompany.getUserCount()){
            if(baseUserService.getBaseUsersByEmployeeId(user.getEmployeeId())==0) {
                user.setCreateTime(new Date());
                user.setCreateBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
               /* BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                String encode = encoder.encode(user.getPassword());*/
                String pwd = user.getPassword();//密码
                String npwd = user.getPassword();//用来循环的密码；
                String encode = hexpwd(pwd, npwd);
                user.setPassword(encode);
                if (baseUserService.addUser(user) != -1) {
                    MdmUserUpdateBaseRolesDto mdmUserUpdateBaseRolesDto = new MdmUserUpdateBaseRolesDto();
                    mdmUserUpdateBaseRolesDto.setId(user.getId());
                    mdmUserUpdateBaseRolesDto.setRids(user.getRids());
                    updateBaseUserBaseRoles(mdmUserUpdateBaseRolesDto);
                } else {
                    return 1/0;
                }
                return 0;
            }else{
                return 1/0;
            }
        }else{
            return 1/0;
        }
    }


    public RestStatus updateBaseUserBaseRoles(MdmUserUpdateBaseRolesDto mdmUserUpdateBaseRolesDto) {
        baseUserService.updateBaseUserBaseRoles(mdmUserUpdateBaseRolesDto.getId().longValue(), mdmUserUpdateBaseRolesDto.getRids());
        return CommonStatus.UPDATE_OK;
    }

    //查询主库公司是能创建多少用户
    public MdmCompany  userCount(){
        String currentDbType = DbContextHolder.getDbType();
        DbContextHolder.setDbType(CommonConstant.MAIN_DB_READ);
        MdmCompany mdmCompany=baseUserService.selectMapCompany(LoginDetailUtils.getCompanyCode());//可创建用户
        DbContextHolder.setDbType(currentDbType);
        return mdmCompany;
    }


    public String hexpwd(String pwd, String npwd) {
        String salt = UUID.randomUUID().toString().substring(0, 6);
        System.out.println(SHA256Util.getSHA256StrJava("G1" + salt + pwd).length());//G1+随机数+密码进行SHA256运算
        Random random = new Random();
        int cycletimes = (int) (random.nextInt(100)) + 100;//后随机数范围变成[ 100~999）；循环次数
        System.out.println(cycletimes);
        String sh256 = "";
        sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd);//G1+随机数+密码进行SHA256运算 循环多少次循环的次数是随机生成的
        for (int i = 0; i <= cycletimes; i++) {
            sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd + sh256);//G1+随机数+密码进行SHA256运算 循环多少次循环的次数是随机生成的
            sh256 = sh256;
            //sh256=SHA256Util.getSHA256StrJava("G1"+cd+"123456");
            //System.out.println(sh256);
        }
        System.out.println(sh256);
        String hex = HexStringUtils.toHex("G1" + salt + cycletimes + sh256);//16进制字符串
        System.out.println("16进制字符串存数据库" + hex);
        return hex;
    }



}
